import { Shape, Rect } from './utils/shape'

const canvas: HTMLCanvasElement = document.querySelector('canvas') as HTMLCanvasElement
const ctx: CanvasRenderingContext2D = canvas.getContext('2d') as CanvasRenderingContext2D

function createHDCanvas(canvas: HTMLCanvasElement, w: number, h: number) {
	const ratio = window.devicePixelRatio || 1
	canvas.width = w * ratio // 实际渲染像素
	canvas.height = h * ratio // 实际渲染像素
	canvas.style.width = `${w}px` // 控制显示大小
	canvas.style.height = `${h}px` // 控制显示大小
	ctx.scale(ratio, ratio)
}
createHDCanvas(canvas, innerWidth, innerHeight)
const options = {
	mode: 'rect',
}
let preNode: Shape | null = null
const mouseDownPosition: { x: number; y: number } = {
	x: 0,
	y: 0,
}
const shapeList: Array<Shape> = []
let activeShape: Shape | null = null
let isDrawing = false
createHDCanvas(canvas, innerWidth, innerHeight)
const resizeCanvas = () => {
	createHDCanvas(canvas, innerWidth, innerHeight)
}

window.addEventListener('resize', () => {
	resizeCanvas()
})

canvas.addEventListener('click', e => {
	shapeList.forEach(shape => {
		if (shape.isInside(e.offsetX, e.offsetY)) {
			shape.emit('click')
		}
	})
})
canvas.addEventListener('mousemove', e => {
	shapeList.forEach(shape => {
		if (shape.isInside(e.offsetX, e.offsetY)) {
			shape.emit('mousemove')
		}
	})
})
// canvas.addEventListener('mousedown', e => {
// 	isDrawing = true
// 	const x: number = e.offsetX
// 	const y: number = e.offsetY
// 	mouseDownPosition.x = x
// 	mouseDownPosition.y = y
// 	// const drawRect = (x: number, y: number) => {
// 	const rect = new Rect({
// 		x: x,
// 		y: y,
// 		width: 0,
// 		height: 0,
// 	})
// 	activeShape = rect
// 	activeShape = rect
// 	activeShape.draw(ctx)
// 	shapeList.push(activeShape as Shape)

// 	rect.on('click', () => {
// 		console.log(1111111)
// 	})
// 	// }
// })
// canvas.addEventListener('mousemove', e => {
// 	if (isDrawing && activeShape) {
// 		const x: number = e.offsetX
// 		const y: number = e.offsetY
// 		const dx: number = x - mouseDownPosition.x
// 		const dy: number = y - mouseDownPosition.y

// 		activeShape.info.width = dx
// 		activeShape.info.height = dy
// 		activeShape.draw(ctx)
// 	}
// })

// canvas.addEventListener('mouseup', e => {
// 	isDrawing = false
// })
// canvas.addEventListener('click', e => {
// 	shapeList.forEach(shape => {})
// })

const rect = new Rect({
	x: 100,
	y: 100,
	width: 100,
	height: 100,
})
rect.on('click', () => {
	console.log(11111111111111)
})
rect.on('mousemove', () => {
	console.log(222222)
})
shapeList.push(rect)

const animate = () => {
	requestAnimationFrame(animate)
	ctx.clearRect(0, 0, canvas.width, canvas.height)
	createHDCanvas(canvas, innerWidth, innerHeight)

	if (shapeList.length > 0) {
		shapeList.forEach(shape => {
			shape.draw(ctx)
		})
	}
}
animate()
